package zack.project.trigger.rpc;

import zack.project.domain.award.service.IAwardService;
import zack.project.domain.strategy.model.entity.RaffleAwardEntity;
import zack.project.domain.strategy.model.entity.RaffleFactorEntity;
import zack.project.domain.strategy.service.IRaffleStrategy;
import zack.project.trigger.api.ILotteryService;
import zack.project.trigger.api.dto.LotteryBaseRequestDTO;
import zack.project.trigger.api.dto.LotteryResponseDTO;
import zack.project.trigger.api.request.Request;
import zack.project.trigger.api.response.Response;
import zack.project.types.enums.ResponseCode;
import zack.project.types.exception.AppException;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;

import javax.annotation.Resource;

/**
 * @author A1793
 */
@Service(version = "1.0")
public class LotteryService implements ILotteryService {

    @Resource
    IRaffleStrategy raffleStrategy;
    @Resource
    IAwardService awardService;

    @Override
    public Response<LotteryResponseDTO> lottery(Request<LotteryBaseRequestDTO> request) {
        try {
            if (request == null ||
                    StringUtils.isBlank(request.getAppToken()) ||
                    StringUtils.isBlank(request.getAppId()) ||
                    request.getData() == null
            ) {
                throw new AppException(ResponseCode.ILLEGAL_PARAMETER.getCode(), ResponseCode.ILLEGAL_PARAMETER.getInfo());
            }
            LotteryBaseRequestDTO lotteryRequestDTO = request.getData();
            if (lotteryRequestDTO.getStrategyId() == null) {
                throw new AppException(ResponseCode.ILLEGAL_PARAMETER.getCode(), ResponseCode.ILLEGAL_PARAMETER.getInfo());
            }
            RaffleAwardEntity raffleAwardEntity =
                    raffleStrategy.performRaffle(RaffleFactorEntity.builder()
                            .strategyId(lotteryRequestDTO.getStrategyId())
                            .userId("system")
                            .build());
            String awardConfig = awardService.queryAwardConfig(raffleAwardEntity.getAwardId());
            return Response.<LotteryResponseDTO>builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .info(ResponseCode.SUCCESS.getInfo())
                    .data(LotteryResponseDTO.builder()
                            .awardResult(awardConfig)
                            .build())
                    .build();
        } catch (AppException e) {
            return Response.<LotteryResponseDTO>builder()
                    .code(e.getCode())
                    .info(e.getInfo())
                    .data(null)
                    .build();

        } catch (Exception e) {
            return Response.<LotteryResponseDTO>builder().code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo()).data(null).build();
        }
    }
}
